package com.igeek.car.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igeek.car.entity.Orders;
import com.igeek.car.mapper.OrdersMapper;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.igeek.car.service.OrdersService;
import com.igeek.car.vo.PageQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.concurrent.atomic.AtomicInteger;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * <p>
 * 订单信息表 服务实现类
 * </p>
 *
 * @author Suzi
 * @since 2024-12-06
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    // 分页条件查询订单信息
    @Transactional(readOnly = true)
    @Override
    public Page<Orders> findPage(PageQueryVO vo) {
        // 1.封装分页数据
        Integer currentPage = vo.getCurrentPage();
        Integer pageSize = vo.getPageSize();
        Page<Orders> page = new Page<>(currentPage, pageSize);

        // 2.封装查询条件
        String queryString = vo.getQueryString();
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.hasLength(queryString), Orders::getOrderNumber, queryString)
                .or()
                .like(StringUtils.hasLength(queryString), Orders::getCustomerName, queryString);

        // 3.执行分页条件查询
        return this.baseMapper.selectPage(page, lambdaQueryWrapper);
    }

    // 新增订单
    @Transactional
    @Override
    public boolean save(Orders order) {
        // 执行新增操作
        int result = this.baseMapper.insert(order);
        return result > 0;
    }

    // 删除订单记录
    @Transactional
    @Override
    public boolean del(Integer id) {
        // 1.检查订单是否存在
        if (ObjectUtils.isEmpty(id) || this.baseMapper.selectById(id) == null) {
            throw new RuntimeException("订单不存在！");
        }

        // 2.执行删除操作
        int result = this.baseMapper.deleteById(id);
        return result > 0;
    }

    // 线程安全的计数器，用于生成订单号的当天排序号
    private static final AtomicInteger COUNTER = new AtomicInteger(0);
    private static final String DATE_FORMAT = "yyyyMMdd";

    @Override
    public String generateOrderNumber() {
        // 获取当前日期并格式化为 yyyyMMdd
        String currentDate = new SimpleDateFormat(DATE_FORMAT).format(new Date());

        // 根据当前计数器生成三位序号，不足补零
        int count = COUNTER.incrementAndGet();
        String sequence = String.format("%03d", count);

        // 生成订单号
        return currentDate + sequence;
    }


    @Override
    public List<Map<String, Object>> getOrderStatistics() {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("dispatch_id AS dispatchId", "COUNT(*) AS orderCount")
                .groupBy("dispatch_id");
        return this.listMaps(queryWrapper);
    }

    @Override
    public List<Map<String, Object>> getDateOrderStatistics() {
        return this.baseMapper.getDateOrderStatistics();
    }

    @Override
    public boolean refundOrder(Integer id) {
        // 查询订单
        Orders order = this.getById(id);
        if (order != null && !"Cancelled".equals(order.getStatus())) {
            // 更新状态为 "Cancelled"
            order.setStatus("Cancelled");
            return this.updateById(order);
        }
        return false;
    }

    @Override
    public boolean rescheduleOrder(Integer id, Orders orderDetails) {
        // 检查订单是否存在
        Orders order = this.getById(id);
        if (order == null) {
            return false;
        }

        // 检查订单状态是否允许改签
        if (!order.getStatus().equals("Pending")) {
            return false;
        }

        // 更新订单信息
        order.setDispatchId(orderDetails.getDispatchId());
        order.setSeatNumber(orderDetails.getSeatNumber());
        // ... 更新其他需要改签的信息

        return this.updateById(order);
    }

    @Override
    public boolean confirmOrder(Integer id) {
        Orders order = this.getById(id);
        if (order == null) {
            return false;
        }
        if (!"Pending".equals(order.getStatus())) {
            return false; // 只有待确认的订单可以被确认
        }
        order.setStatus("Completed");
        return this.updateById(order);
    }
}